package com.lw.leetcode.tree.b;

import com.lw.leetcode.linked.Node;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * Created with IntelliJ IDEA.
 * 429. N 叉树的层序遍历
 * 广度搜索例题
 *
 * @author liw
 * @version 1.0
 * @date 2021/11/5 11:29
 */
public class LevelOrder {

    public List<List<Integer>> levelOrder(Node root) {
        List<List<Integer>> lists = new ArrayList<>();
        if (root == null) {
            return lists;
        }
        Queue<Node> queue = new LinkedList<>();
        queue.add(root);
        queue.add(null);
        List<Integer> item = new ArrayList<>();
        while (queue.size() > 1) {
            Node node = queue.poll();
            if (node == null) {
                lists.add(item);
                item = new ArrayList<>();
                queue.add(null);
            } else {
                item.add(node.val);
                if (node.children != null) {
                    queue.addAll(node.children);
                }
            }
        }
        lists.add(item);
        return lists;
    }

}
